package com.project.frba.bifront.client.view.dashboard;

import java.util.Collection;

import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Composite;
import com.gwtext.client.core.EventObject;
import com.gwtext.client.data.FieldDef;
import com.gwtext.client.data.IntegerFieldDef;
import com.gwtext.client.data.Record;
import com.gwtext.client.data.RecordDef;
import com.gwtext.client.data.Store;
import com.gwtext.client.data.StringFieldDef;
import com.gwtext.client.widgets.Button;
import com.gwtext.client.widgets.Panel;
import com.gwtext.client.widgets.Window;
import com.gwtext.client.widgets.event.ButtonListenerAdapter;
import com.gwtext.client.widgets.form.ComboBox;
import com.gwtext.client.widgets.form.Label;
import com.gwtext.client.widgets.form.event.ComboBoxListenerAdapter;
import com.gwtext.client.widgets.layout.HorizontalLayout;
import com.project.frba.bifront.client.model.Dashboard;
import com.project.frba.bifront.client.rpc.DashboardServices;
import com.project.frba.bifront.client.rpc.DashboardServicesAsync;
import com.project.frba.bifront.client.view.MessageWindow;

public class ChartToDashboardWindow extends Composite {

	private Window mainWindow = new Window();
	private Collection<Dashboard> myDashboards;
	private ComboBox cbDashboard = new ComboBox();
	private ComboBox cbFreePositions = new ComboBox();
	private String chartSerialized = null;
	private Store storePosition;
	private RecordDef recordDefPosition;
	private Dashboard selectedDashboard = null;
	private Integer selectedPosition = null;
	private DashboardServicesAsync dashboardServices = (DashboardServicesAsync)GWT.create(DashboardServices.class);

	private Button btAccept = new Button("Aceptar");
	private Button btCancel = new Button("Cancelar");
	

	public ChartToDashboardWindow(Collection<Dashboard> dashboards){
		this.myDashboards = dashboards;
		
		FieldDef[] fieldDefs = new FieldDef[]{
				new StringFieldDef("id"), 
				new StringFieldDef("name"), 
				new IntegerFieldDef("type")
				};
		
		RecordDef recordDef = new RecordDef(fieldDefs);
		Store store = new Store(recordDef);
		cbDashboard.setStore(store);
		cbDashboard.setEmptyText("Seleccione un tablero...");
		
		for (Dashboard dashboard : dashboards) {
			System.out.println(dashboard.getName());
			store.add(recordDef.createRecord(new Object[]{
					dashboard.getId().toString(),
					dashboard.getName(), 
					dashboard.getType()
					}));
			store.commitChanges();
		}
		
		cbDashboard.setDisplayField("name"); 
        cbDashboard.setMode(ComboBox.LOCAL); 
        cbDashboard.setTriggerAction(ComboBox.ALL); 
		loadActions();
		
		//Dashboard Selection Panel
		Panel selectDashboardPanel = new Panel();
		selectDashboardPanel.setLayout(new HorizontalLayout(3));
		selectDashboardPanel.setWidth("100%");
		selectDashboardPanel.setHeight(30);
		Label lblDashboards = new Label("Mis tableros");
		selectDashboardPanel.add(lblDashboards);
		selectDashboardPanel.add(cbDashboard);
		mainWindow.add(selectDashboardPanel);
		
		//Dashboard type configuration Panel
		Panel confTypePanel = new Panel();
		confTypePanel.setLayout(new HorizontalLayout(3));
		FieldDef[] fieldDefsPosition = new FieldDef[]{new IntegerFieldDef("position")};
		recordDefPosition = new RecordDef(fieldDefsPosition);
		storePosition = new Store(recordDef);
		cbFreePositions.setStore(storePosition);
		cbFreePositions.setMode(ComboBox.LOCAL); 
		cbFreePositions.setTriggerAction(ComboBox.ALL); 
		cbFreePositions.setDisplayField("position");
		confTypePanel.add(new Label("Posiciones Libres"));		
		confTypePanel.add(cbFreePositions);
		confTypePanel.setBorder(false);
		confTypePanel.setWidth("100%");
		confTypePanel.setHeight(100);
		mainWindow.add(confTypePanel);
		
		
		mainWindow.setWidth(320);
		mainWindow.setHeight(140);
		mainWindow.setResizable(false);
		mainWindow.setPaddings(3);
		mainWindow.setTitle("Enviar a tablero de comando");
		mainWindow.setButtons(new Button[]{btAccept, btCancel});
		initWidget(mainWindow);
		
	}

	private void loadActions() {
		cbDashboard.addListener(new ComboBoxListenerAdapter(){
			public void onSelect(ComboBox comboBox, Record record, int index) {
				String id = record.getAsString("id");
				Integer type = record.getAsInteger("type");
				
				for (Dashboard dashboard : myDashboards) {
					if(dashboard.getId().toString().equals(id) && dashboard.getType().equals(type)){
						selectedDashboard = dashboard;
						break;
					}
				}
				
				storePosition.removeAll();
				for (Integer freePosition : selectedDashboard.getFreePositions()) {
					storePosition.add(recordDefPosition.createRecord(new Object[]{freePosition}));
					storePosition.commitChanges();
				}
			}
		});
		
		cbFreePositions.addListener(new ComboBoxListenerAdapter(){
			public void onSelect(ComboBox comboBox, Record record, int index) {
				selectedPosition = record.getAsInteger("position");
			}
		});
		
		btAccept.addListener(new ButtonListenerAdapter(){
			public void onClick(Button button, EventObject e) {
				if(selectedDashboard != null && selectedPosition != null){
					Long dashboardId = selectedDashboard.getId();
					Integer position = selectedPosition;
					Integer dashboardType = selectedDashboard.getType();
					AsyncCallback<Boolean> callback = new AsyncCallback<Boolean>(){
						public void onFailure(Throwable caught) {
							new MessageWindow("El servicio ha fallado, intente nuevamente.");							
						}
						public void onSuccess(Boolean result) {
							if(result.equals(true)){
								new MessageWindow("Su grafico se ha guardado satisfactoriamente.");
								mainWindow.close();
							} else {
								new MessageWindow("No se pudo guardar su grafico.");
								
							}
						}
					};
					
					dashboardServices.addGraphicToDashboard(chartSerialized, dashboardId, position, dashboardType, callback);
				}
			}
		});
		
		btCancel.addListener(new ButtonListenerAdapter(){
			public void onClick(Button button, EventObject e) {
				mainWindow.close();
			}
		});

	}

	public void show() {
		mainWindow.show();
		
	}

	public String getChartSerialized() {
		return chartSerialized;
	}

	public void setChartSerialized(String chartSerialized) {
		this.chartSerialized = chartSerialized;
	}
}
